package com.gsoe.problem.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gsoe.base.enumeration.ExamStatus;
import com.gsoe.base.exception.ProblemException;
import com.gsoe.base.model.User;
import com.gsoe.base.utils.UserUtil;
import com.gsoe.problem.client.JudgeClient;
import com.gsoe.problem.dto.JudgeExamDTO;
import com.gsoe.problem.dto.SubmitDTO;
import com.gsoe.problem.dto.TeacherCommentDTO;
import com.gsoe.problem.dto.UpdateScoreDTO;
import com.gsoe.problem.mapper.ExamMapper;
import com.gsoe.problem.mapper.ExamRegisterUserMapper;
import com.gsoe.problem.po.Exam;
import com.gsoe.problem.po.ExamProblem;
import com.gsoe.problem.po.ExamRegisterUser;
import com.gsoe.problem.service.ExamProblemService;
import com.gsoe.problem.service.ExamRegisterUserService;
import com.gsoe.problem.vo.ExamDetailVO;
import com.gsoe.problem.vo.ExamResultVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 已注册考试学生信息表 服务实现类
 * </p>
 *
 * @author xiaoma
 * @since 2024-10-27
 */
@Service
public class ExamRegisterUserServiceImpl extends ServiceImpl<ExamRegisterUserMapper, ExamRegisterUser> implements ExamRegisterUserService {
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private ExamRegisterUserMapper examRegisterUserMapper;
/*    @Autowired
    private JudgeClient judgeClient;

    @Autowired
    ExamProblemService examProblemService;*/


    @Override
    public void cancelExam(Long examId) {
        User loginUser = UserUtil.getLoginUser();
        Exam exam = examMapper.selectById(examId);
        if(exam==null)throw new ProblemException("cancelExam：考试不存在");
        if(exam.getBeginTime().isBefore(LocalDateTime.now())){
            throw new ProblemException("cancelExam：考试已开始");
        }

        remove(new QueryWrapper<ExamRegisterUser>()
                .eq("exam_id", examId)
                .eq("user_id", loginUser.getId())
        );
    }

    @Override
    public void signUpExam(Long examId) {
        User loginUser = UserUtil.getLoginUser();
        ExamRegisterUser examRegisterUser = lambdaQuery()
                .eq(ExamRegisterUser::getExamId, examId)
                .eq(ExamRegisterUser::getUserId, loginUser.getId())
                .one();

        if(examRegisterUser!=null && examRegisterUser.getStatus()!= ExamStatus.FAIL){
            throw new ProblemException("signUpExam:注册失败，已经注册过了");
        }

        Exam exam = examMapper.selectById(examId);

        if(exam==null || exam.getEndTime().isBefore(LocalDateTime.now())){
            throw new ProblemException("signUpExam:未找到考试或者考试已经结束");
        }

        examRegisterUser=new ExamRegisterUser();
        examRegisterUser.setExamId(examId);
        examRegisterUser.setUserId(loginUser.getId());
        examRegisterUser.setUserName(loginUser.getUserName());
        examRegisterUser.setStatus(ExamStatus.JOIN);
        save(examRegisterUser);
    }

    @Override
    public void submit(SubmitDTO submitDTO) {
        User loginUser = UserUtil.getLoginUser();
        examRegisterUserMapper.updateStatus(submitDTO.getTextId(),loginUser.getId());
    }

    @Override
    public ExamDetailVO getUserExamDetail(Long examId) {
        ExamDetailVO examDetailVO=new ExamDetailVO();
        Exam exam = examMapper.selectById(examId);
        if(exam==null){
            throw new ProblemException("getUserExamDetail:无此id记录");
        }
        BeanUtils.copyProperties(exam,examDetailVO);

        List<ExamRegisterUser> list = lambdaQuery()
                .eq(ExamRegisterUser::getExamId, examId)
                .list();
        examDetailVO.setExamRegisterUserList(list);
        return examDetailVO;
    }

    @Override
    public void addTeachComment(TeacherCommentDTO teacherCommentDTO) {
        Long id = teacherCommentDTO.getId();
        String teacherComment = teacherCommentDTO.getComment();
        ExamRegisterUser examRegisterUser = getById(id);
        if(examRegisterUser==null){throw new ProblemException("addTeachComment:未找到记录");}
        examRegisterUser.setTeacherComment(teacherComment);
        updateById(examRegisterUser);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        ExamRegisterUser examRegisterUser = getById(id);
        if(examRegisterUser==null){throw new ProblemException("updateStatus:未找到记录");}
        examRegisterUser.setStatus(status);
        updateById(examRegisterUser);
    }

    @Override
    public void updateScore(UpdateScoreDTO updateScoreDTO) {
        Integer score = updateScoreDTO.getScore();
        Long userId = updateScoreDTO.getUserId();
        Long examId = updateScoreDTO.getExamId();

        ExamRegisterUser examRegisterUser = lambdaQuery()
                .eq(ExamRegisterUser::getUserId, userId)
                .eq(ExamRegisterUser::getExamId, examId)
                .one();
        if(examRegisterUser==null){throw new ProblemException("updateScore:无此注册用户记录");}
        examRegisterUser.setScore(examRegisterUser.getScore()+score);
        updateById(examRegisterUser);
    }

    @Override
    public List<ExamResultVO> getUserExamList(Long userId) {
        /*该用户参加过的考试*/
        List<Long> listExamId=examRegisterUserMapper.getExamId(userId);
        List<ExamResultVO> getUserExamList=new ArrayList<>();
        for (Long examId : listExamId) {
            /*传入其中一次考试的考试号,获取参加此次考试的学生*/
            ExamResultVO examResultVO = new ExamResultVO();
            examResultVO.setId(examId);
            List<ExamRegisterUser> examRegisterUserList=examRegisterUserMapper.getExamRegisterUser(examId);
            /*获取排名*/
            ExamRegisterUser examRegisterUser = new ExamRegisterUser();
            examRegisterUser.setUserId(userId);
            int i = examRegisterUserList.indexOf(examRegisterUser);
            Integer ranking=i+1;
            examResultVO.setRanking(ranking);

            /*获取取得的分数*/
            examResultVO.setGetScore(examRegisterUserList.get(i).getScore());

            /*获取总分数*///再次调用mapper 查询 名称 并且顺便查其他
            Exam exam= examMapper.getExamInfo(examId);
            examResultVO.setExamName(exam.getExamName());
            examResultVO.setScore(exam.getScore());
            /*参加考试的总人数*/
            int peopleNum = examRegisterUserList.size();
            examResultVO.setPeopleNum(peopleNum);

            /*将类存入集合当中*/
            getUserExamList.add(examResultVO);
        }
        return getUserExamList;
    }
}
